package com.mrd.gtimp.sup.action;

import com.mrd.constant.MsgConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.base.service.CompanyBiz;
import com.mrd.gtimp.sup.entity.SupCustomer;
import com.mrd.gtimp.sup.service.SupCustomerBiz;
import com.mrd.util.LoginUtil;
import com.mrd.util.result.SupAddBatchResult;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */

@Controller
@RequestMapping("/sup")
public class SupCustomerAction {
    private static final long serialVersionUID = 1L;

    private static final int UCOMPANYLIST_MAX = 2;
    @Resource
    private SupCustomerBiz supCustomerBiz;

    @Resource
    private CompanyBiz companyBiz;

    /**
     * 默认访问入口
     */
    @RequestMapping("/supCustomer-main")
    public String main() {
        return "/gtimp/sup/supCustomerList";
    }

    /**
     * 默认新增修改入口
     */
    @RequestMapping("/supCustomer-manage")
    public String manage() {
        return "/gtimp/sup/supCustomerManage";
    }

    /**
     * 新增入口
     */
    @RequestMapping("/supCustomer-queryToManage")
    public String queryToManage() {
        return "/gtimp/sup/supCustomerQueryList";
    }

    /**
     * 新增或修改信息
     */
    //// TODO: 2016/8/15  @Permissions
//    @Permissions(permissionsId = RoleConstants.SUP_CUSTOMER_SAVE)
    @RequestMapping("/supCustomer-saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(SupCustomer supCustomer) {
        Result msg;
        // if(checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
        try {
            if (StringUtils.isEmpty(supCustomer.getID())) {  // 新增操作
                supCustomer.setCOM_ID(LoginUtil.getLoginUser().getCompany().getId());
                supCustomer.setCREATOR(LoginUtil.getLoginUser().getAccount());
                supCustomer.setCTIME(new Date());
                supCustomer.setID(null);
            } else {  // 修改操作
                supCustomer.setMODIFIER(LoginUtil.getLoginUser().getAccount());
                supCustomer.setMTIME(new Date());
            }
            supCustomerBiz.saveOrupdateEntity(supCustomer);
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + e.getMessage());
        }
        return msg;
    }

    /**
     * 批量添加
     */
    // @Permissions(permissionsId = RoleConstants.SUP_CUSTOMER_SAVE)
    @RequestMapping("/supCustomer-addBatch")
    @ResponseBody
    public Result addBatch() {
        // if(checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
        Result msg;
        try {
            String COM_ID = LoginUtil.getLoginUser().getCompany().getId();
            String CREATOR = LoginUtil.getLoginUser().getAccount();

            String ids = HttpUtils.getRequest().getParameter("id");
            String[] idArr = ids.split(",");
            SupAddBatchResult result = new SupAddBatchResult();
            if (idArr != null && idArr.length > 0) {
                result = supCustomerBiz.addBatch(idArr, COM_ID, CREATOR);
                msg = Result.newSuccessInstance(result.toString());
            } else {
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + result.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + e.getMessage());
        }
        return msg;
    }

    /**
     * 编辑信息
     */
    @RequestMapping("/supCustomer-find")
    @ResponseBody
    public SupCustomer find(SupCustomer supCustomer) {
        if (null != supCustomer) {
            if (StringUtils.isNotEmpty(supCustomer.getID())) {
                try {
                    supCustomer = supCustomerBiz.findEntityById(supCustomer.getID());
                    return supCustomer;
                } catch (QueryException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 删除信息
     */
    //// TODO: 2016/8/15   @Permissions
//    @Permissions(permissionsId = RoleConstants.SUP_CUSTOMER_DEL)
    @RequestMapping("/supCustomer-del")
    @ResponseBody
    public Result del() {
        Result msg;
        // if(checkRight(RoleConstants.SUP_CUSTOMER_DEL)) {
        try {
            String ids = HttpUtils.getRequest().getParameter("id");
            String[] idArr = ids.split(",");
            List<SupCustomer> del = new ArrayList<>();
            for (String string : idArr) {
                SupCustomer supCustomer=new SupCustomer();
                supCustomer.setID(string);
                del.add(supCustomer);
            }
            supCustomerBiz.delete(del);
            msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
        }
        return msg;
    }

    /**
     * 查询
     */
    @RequestMapping("/supCustomer-findList")
    @ResponseBody
    public Page<SupCustomer> findList(Jqgrid jqgrid) {
        String comId = LoginUtil.getLoginUser().getCompany().getId();// get from user
        try {
            SearchRule rule = new SearchRule("COM_ID", SearchRuleOption.eq, comId);
            jqgrid.addRule(rule);
//            page = initPage(supCustomerBiz.findEntityCount(filters));
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }
//            supCustomers = supCustomerBiz.findEntityByFilter(page.getCurrentPageStartNo(), page
//                    .getPageSize(), filters, order);
            Page<SupCustomer> supCustomers = supCustomerBiz.findByJqgrid(jqgrid);
            if (null != supCustomers && supCustomers.getSize() > 0) {
                return supCustomers;
            }
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 供应商查找客户添加到客户关系列表
     */
    @RequestMapping("/supCustomer-findUCompanyList")
    @ResponseBody
    public Page<Company> findUCompanyList(Jqgrid jqgrid) {
        Result msg;
        try {
            if (null != jqgrid && jqgrid.getFilters()!= null) {
//                int counts = companyBiz.findEntityCount(filters);
//                page = initPage(counts);
//                Order order = new Order();
//                if (null != sidx && !"".equals(sidx)) {
//                    order.add(sidx, sord);
//                }
//                Pageable page = new PageRequest(0, 15, Sort.Direction.DESC, "id");
//                Jqgrid jqgrid = new Jqgrid(filters, page);
//                if (counts <= UCOMPANYLIST_MAX) {
//                    companys = companyBiz.findEntityByFilter(page.getCurrentPageStartNo(), page
//                            .getPageSize(), filters, order);
                Page<Company> companys = companyBiz.findByJqgrid(jqgrid);
                if(null!=companys&&companys.getSize()>0){
                    return  companys;
                }
                } else {
                    msg = Result.newFailInstance("请使用更详细的公司名称查询");
                    return (Page<Company>) msg;
                }
            } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;

    }

    @Resource
    public void setSupCustomerBiz(SupCustomerBiz supCustomerBiz) {
        this.supCustomerBiz = supCustomerBiz;
    }

    public CompanyBiz getCompanyBiz() {
        return companyBiz;
    }

    @Resource
    public void setCompanyBiz(CompanyBiz companyBiz) {
        this.companyBiz = companyBiz;
    }

}
